﻿/**

 * Copyright (c) 2015-2016, FastDev 刘强 (fastdev@163.com).

 *

 * Licensed under the Apache License, Version 2.0 (the "License");

 * you may not use this file except in compliance with the License.

 * You may obtain a copy of the License at

 *

 *      http://www.apache.org/licenses/LICENSE-2.0

 *

 * Unless required by applicable law or agreed to in writing, software

 * distributed under the License is distributed on an "AS IS" BASIS,

 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 * See the License for the specific language governing permissions and

 * limitations under the License.

 */

using MsgPack;
using MsgPack.Serialization;
using OF.DistributeService.Core.Common;
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Formatting;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Web;
using System.Web.Http;
using System.Web.Security;
using System.Web.SessionState;

namespace OF.DistributeService.Core.Common
{
    public class MessagePackMediaTypeFormatter : MediaTypeFormatter
    {
        Func<Type, bool> IsAllowedType = (t) =>
        {
            if (!t.IsAbstract && !t.IsInterface && t != null && !t.IsNotPublic)
                return true;
            if (typeof(IEnumerable).IsAssignableFrom(t))
                return true;
            return false;
        };
        public MessagePackMediaTypeFormatter()
        {
            SupportedMediaTypes.Add(new MediaTypeHeaderValue(Util.MsgPackContentType));
        }
        public override bool CanWriteType(Type type)
        {
            if (type == null)
                throw new ArgumentNullException("Type is null");
            return IsAllowedType(type);
        }
        public override Task WriteToStreamAsync(Type type, object value, System.IO.Stream stream, HttpContent content, TransportContext transportContext)
        {
            if (type == null)
                throw new ArgumentNullException("type is null");
            if (stream == null)
                throw new ArgumentNullException("Write stream is null");
            var tcs = new TaskCompletionSource<object>();
            if (type != typeof(string) && typeof(IEnumerable).IsAssignableFrom(type))
            {
                value = (value as IEnumerable<object>).ToList();
            }
            var serializer = MessagePackSerializer.Get<dynamic>();
            serializer.Pack(stream, value);
            tcs.SetResult(null);
            return tcs.Task;
        }
        public override Task<object> ReadFromStreamAsync(Type type, Stream stream, HttpContent content, IFormatterLogger formatterLogger)
        {
            var tcs = new TaskCompletionSource<object>();
            if (content.Headers != null && content.Headers.ContentLength == 0)
            {
                return null;
            }
            try
            {
                var serializer = MessagePackSerializer.Get(type);
                object result;
                using (var mpUnpacker = Unpacker.Create(stream))
                {
                    mpUnpacker.Read();
                    result = serializer.UnpackFrom(mpUnpacker);
                }
                tcs.SetResult(result);
            }
            catch (System.Exception e)
            {
                if (formatterLogger == null) throw;
                formatterLogger.LogError(String.Empty, e.Message);
                tcs.SetResult(GetDefaultValueForType(type));
            }
            return tcs.Task;
        }
        public override bool CanReadType(Type type)
        {
            if (type == null)
                throw new ArgumentNullException("type is null");
            return IsAllowedType(type);
        }
    }
}
